package com.gitee.melin.bee.core.grpc.error;

import io.grpc.ForwardingServerCall;
import io.grpc.Metadata;
import io.grpc.ServerCall;
import io.grpc.Status;

/** huaixin 2022/1/28 9:54 AM */
public class GrpcExceptionServerCall<ReqT, RespT> extends ForwardingServerCall.SimpleForwardingServerCall<ReqT, RespT> {

    private final GrpcExceptionResponseHandler exceptionHandler;

    /**
     * Creates a new exception handling grpc server call.
     *
     * @param delegate The call to delegate to (Required).
     * @param exceptionHandler The exception handler to use (Required).
     */
    protected GrpcExceptionServerCall(
            final ServerCall<ReqT, RespT> delegate, final GrpcExceptionResponseHandler exceptionHandler) {

        super(delegate);
        this.exceptionHandler = exceptionHandler;
    }

    @Override
    public void close(final Status status, final Metadata trailers) {
        // For error responses sent via StreamObserver#onError
        if (status.getCode() == Status.Code.UNKNOWN && status.getCause() != null) {
            final Throwable cause = status.getCause();
            this.exceptionHandler.handleError(delegate(), cause);
        } else {
            super.close(status, trailers);
        }
    }
}
